package realphone

import (
	"bytes"
	"cloud_android_backend/pkg/models/country"
	"cloud_android_backend/pkg/models/products"
	proxy2 "cloud_android_backend/pkg/models/proxy"
	"cloud_android_backend/pkg/models/realphone"
	"cloud_android_backend/pkg/models/resources"
	"cloud_android_backend/pkg/utils"
	"encoding/json"
	"fmt"
	"github.com/golang/glog"
	"github.com/lucasjones/reggen"
	"io/ioutil"
	"math/rand"
	"modules.tenxcloud.com/common/composite"
	"net/http"
	"strconv"
	"strings"
	"time"
)

type RealPhoneListFormat struct {
	Brand  string                        `json:"brand"`
	Models []realphone.RealPhoneTemplate `json:"models"`
}

func GetRealPhoneListByAndroidVersion(androidVersion int) ([]RealPhoneListFormat, error) {
	db, err := composite.Database.GetOrm()
	if err != nil {
		return nil, err
	}
	realPhoneModel := &realphone.RealPhoneTemplate{}
	list, _, err := realPhoneModel.GetListByAndroidImageVersion(db, androidVersion, 0, 0)
	if err != nil {
		return nil, err
	}
	brandListMap := make(map[string][]realphone.RealPhoneTemplate)
	for _, model := range list {
		if _, ok := brandListMap[model.Brand]; ok {
			brandListMap[model.Brand] = append(brandListMap[model.Brand], model)
		} else {
			brandListMap[model.Brand] = []realphone.RealPhoneTemplate{
				model,
			}
		}
	}
	var brandList []RealPhoneListFormat
	for brand, models := range brandListMap {
		brandList = append(brandList, RealPhoneListFormat{
			Brand:  brand,
			Models: models,
		})
	}
	return brandList, nil
}

func ChangeRealPhoneModelAndClearData(instanceUseId int64, ModelId int64, UserId string) error {
	db, err := composite.Database.GetOrm()
	if err != nil {
		return err
	}
	instanceModel := &resources.InstanceUses{Id: instanceUseId}
	err = instanceModel.GetByIdWithInstanceInfo(db)
	if err != nil {
		glog.Errorf("get instance failed:err %v", err)
		return err
	}
	if instanceModel.UserId != UserId {
		return fmt.Errorf("no permission")
	}
	androidVersion, _ := strconv.Atoi(instanceModel.Instances.ImageTag)
	if androidVersion == 0 {
		androidVersion = 13
	}
	productModel := &products.Products{Id: instanceModel.Instances.ProductId}
	err = productModel.GetById(db)
	if err != nil {
		return err
	}
	var containerResourceOpsParam ContainerResourceOpsParam
	containerResourceOpsParam.Name = instanceModel.Instances.Name
	containerResourceOpsParam.Ip = instanceModel.Instances.Ip
	containerResourceOpsParam.CpuLimit = &(instanceModel.Instances.CpuCores)
	containerResourceOpsParam.MemoryLimit = &(instanceModel.Instances.Memory)
	containerResourceOpsParam.Hostname = instanceModel.Instances.Name
	containerResourceOpsParam.MacvlanName = instanceModel.Instances.MacVlanName
	containerResourceOpsParam.ContainerIndex = &(instanceModel.Instances.Index)
	storage := int(instanceModel.Instances.Storage)
	containerResourceOpsParam.DiskOpsParam = &BaseLvmDiskOpsParam{
		ContainerPerStorageSize: &storage,
	}
	containerResourceOpsParam.StorageLimit = storage
	containerResourceOpsParam.ImageRepository = "img-25070992425" //TODO 暂时写死
	containerResourceOpsParam.ImageTag = "latest"
	containerResourceOpsParam.Mac, _ = utils.GenerateRandomMAC()
	containerResourceOpsParam.DeviceAndroidProps = map[string]string{"persist.sys.cloud.madb_enable": "1", "persist.sys.locale": "zh-CN", "ro.boot.cluster_code": "1234et", "ro.build.version.security_patch": "2025-06-05", "ro.vendor.build.security_patch": "2025-06-05"}
	updateFiles := map[string]interface{}{
		"mac": containerResourceOpsParam.Mac,
	}
	realPhoneModel := &realphone.RealPhoneTemplate{Id: ModelId}
	err = realPhoneModel.GetById(db)
	if err != nil {
		return err
	}
	containerResourceOpsParam.DownloadUrlOfADI = realPhoneModel.AdiTemplateDownloadUrl
	containerResourceOpsParam.PasswordOfADI = realPhoneModel.AdiTemplatePwd
	certificateModel := &realphone.CertificateRepository{
		CertificateLevel: 3,
	}
	err = certificateModel.GetOneRandByLevel(db)
	if err != nil {
		return err
	}
	layoutArr := strings.Split(strings.Replace(realPhoneModel.ScreenLayoutCode, "realdevice_", "", -1), "x")
	width := instanceModel.Instances.Width
	height := instanceModel.Instances.Height
	dpi := instanceModel.Instances.Dpi
	if layoutArr != nil && len(layoutArr) == 3 {
		width, _ = strconv.Atoi(layoutArr[0])
		height, _ = strconv.Atoi(layoutArr[1])
		dpi, _ = strconv.Atoi(layoutArr[2])
	}
	containerResourceOpsParam.AndroidCertData = certificateModel.Certificate

	containerResourceOpsParam.Width = &width
	containerResourceOpsParam.Height = &height
	containerResourceOpsParam.Fps = &(instanceModel.Instances.Fps)
	containerResourceOpsParam.Dpi = &dpi
	updateFiles["adi_template_id"] = realPhoneModel.Id

	containerResourceOpsParam.GameServerAddress = "192.168.1.1:8081"
	containerResourceOpsParam.Dns1 = "8.8.8.8"
	containerResourceOpsParam.Ports = strconv.Itoa(instanceModel.Instances.AdbPort)
	clearContainerData := true
	containerResourceOpsParam.ClearContainerData = &clearContainerData
	go func(param ContainerResourceOpsParam) {
		url := fmt.Sprintf("http://%s:%d/container/lifecycle/recreate", instanceModel.Instances.Machine.Ip, instanceModel.Instances.Machine.Port)
		// 将数据编码为 JSON
		jsonData, err := json.Marshal(param)
		if err != nil {
			fmt.Printf("Get system info failed! json marshall err:%v", err)
			return
		}

		// 创建 POST 请求
		resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
		if err != nil {
			fmt.Printf("Get system info failed! post err:%v", err)
			return
		}
		defer resp.Body.Close()
		if resp.StatusCode != http.StatusOK {
			fmt.Printf("Get system info failed! status code:%d", resp.StatusCode)
			return
		}
		// 读取响应
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			fmt.Printf("Get system info failed! read body err:%v", err)
			return
		}
		fmt.Println(string(body))
		return
	}(containerResourceOpsParam)
	instancesModel := &instanceModel.Instances

	updateFiles["dpi"] = *containerResourceOpsParam.Dpi
	updateFiles["width"] = *containerResourceOpsParam.Width
	updateFiles["height"] = *containerResourceOpsParam.Height
	updateFiles["fps"] = *containerResourceOpsParam.Fps

	//instancesModel.Dpi = *containerResourceOpsParam.Dpi
	//instancesModel.Width = *containerResourceOpsParam.Width
	//instancesModel.Height = *containerResourceOpsParam.Height
	//instancesModel.Fps = *containerResourceOpsParam.Fps
	//instancesModel.AdiTemplateId = realPhoneModel.Id
	err = instancesModel.UpdatePartFields(db, updateFiles)
	if err != nil {
		glog.Errorf("update instance failed:err %v", err)
		return err
	}
	err = instanceModel.UpdatePartFields(db, map[string]interface{}{"state": 0, "operate_time": time.Now()})
	if err != nil {
		glog.Errorf("update instance failed:err %v", err)
		return err
	}
	return nil
}
func ChangeRealPhoneModel(instanceUseId, modelId int64, UserId string) error {
	db, err := composite.Database.GetOrm()
	if err != nil {
		return err
	}
	instanceModel := &resources.InstanceUses{Id: instanceUseId}
	err = instanceModel.GetByIdWithInstanceInfo(db)
	if err != nil {
		glog.Errorf("get instance failed:err %v", err)
		return err
	}
	if instanceModel.UserId != UserId {
		return fmt.Errorf("no permission")
	}
	realPhoneModel := &realphone.RealPhoneTemplate{Id: modelId}
	err = realPhoneModel.GetById(db)
	if err != nil {
		return err
	}
	var containerResourceOpsParam ContainerResourceOpsParam
	containerResourceOpsParam.Name = instanceModel.Instances.Name
	containerResourceOpsParam.Ip = instanceModel.Instances.Ip
	containerResourceOpsParam.CpuLimit = &(instanceModel.Instances.CpuCores)
	containerResourceOpsParam.MemoryLimit = &(instanceModel.Instances.Memory)
	containerResourceOpsParam.Hostname = instanceModel.Instances.Name
	containerResourceOpsParam.MacvlanName = instanceModel.Instances.MacVlanName
	containerResourceOpsParam.ContainerIndex = &(instanceModel.Instances.Index)
	storage := int(instanceModel.Instances.Storage)
	containerResourceOpsParam.DiskOpsParam = &BaseLvmDiskOpsParam{
		ContainerPerStorageSize: &storage,
	}
	containerResourceOpsParam.StorageLimit = storage
	containerResourceOpsParam.ImageRepository = instanceModel.Instances.Image //TODO 暂时写死
	containerResourceOpsParam.ImageTag = instanceModel.Instances.ImageTag
	containerResourceOpsParam.DownloadUrlOfADI = realPhoneModel.AdiTemplateDownloadUrl
	containerResourceOpsParam.PasswordOfADI = realPhoneModel.AdiTemplatePwd
	containerResourceOpsParam.DeviceAndroidProps = map[string]string{"persist.sys.cloud.madb_enable": "1", "ro.boot.cluster_code": "ZEG3650947", "persist.sys.locale": "zh-CN", "ro.build.version.security_patch": "2025-06-05", "ro.vendor.build.security_patch": "2025-06-05", "ro.sys.cloud.proxy.data": "||||false", "ro.sys.cloud.proxy.mode": "vpn"}
	if instanceModel.ProxyId != 0 {
		props, err := GetCountryParamsForInstance(instanceModel.Id)
		if err != nil {
			fmt.Printf("get proxy country params failed:err %v", err)
			//return err
		}
		for k, v := range props {
			containerResourceOpsParam.DeviceAndroidProps[k] = v
		}
	}
	certificateModel := &realphone.CertificateRepository{
		CertificateLevel: 3,
	}
	err = certificateModel.GetOneRandByLevel(db)
	if err != nil {
		return err
	}
	layoutArr := strings.Split(strings.Replace(realPhoneModel.ScreenLayoutCode, "realdevice_", "", -1), "x")
	width := instanceModel.Instances.Width
	height := instanceModel.Instances.Height
	dpi := instanceModel.Instances.Dpi
	if layoutArr != nil && len(layoutArr) == 3 {
		width, _ = strconv.Atoi(layoutArr[0])
		height, _ = strconv.Atoi(layoutArr[1])
		dpi, _ = strconv.Atoi(layoutArr[2])
	}
	containerResourceOpsParam.AndroidCertData = certificateModel.Certificate
	containerResourceOpsParam.Mac = instanceModel.Instances.Mac
	containerResourceOpsParam.Width = &width
	containerResourceOpsParam.Height = &height
	containerResourceOpsParam.Fps = &(instanceModel.Instances.Fps)
	containerResourceOpsParam.Dpi = &dpi
	containerResourceOpsParam.GameServerAddress = "192.168.1.1:8081"
	containerResourceOpsParam.Dns1 = "8.8.8.8"
	containerResourceOpsParam.Ports = strconv.Itoa(instanceModel.Instances.AdbPort)
	go func(param ContainerResourceOpsParam) {
		url := fmt.Sprintf("http://%s:%d/container/lifecycle/recreate", instanceModel.Instances.Machine.Ip, instanceModel.Instances.Machine.Port)
		// 将数据编码为 JSON
		jsonData, err := json.Marshal(param)
		if err != nil {
			fmt.Printf("Get system info failed! json marshall err:%v", err)
			return
		}

		// 创建 POST 请求
		resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
		if err != nil {
			fmt.Printf("Get system info failed! post err:%v", err)
			return
		}
		defer resp.Body.Close()
		if resp.StatusCode != http.StatusOK {
			fmt.Printf("Get system info failed! status code:%d", resp.StatusCode)
			return
		}
		// 读取响应
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			fmt.Printf("Get system info failed! read body err:%v", err)
			return
		}
		fmt.Println(string(body))
		return
	}(containerResourceOpsParam)
	instancesModel := &instanceModel.Instances
	updateFiles := map[string]interface{}{
		"dpi":             *containerResourceOpsParam.Dpi,
		"width":           *containerResourceOpsParam.Width,
		"height":          *containerResourceOpsParam.Height,
		"fps":             *containerResourceOpsParam.Fps,
		"adi_template_id": realPhoneModel.Id,
	}
	//instancesModel.Dpi = *containerResourceOpsParam.Dpi
	//instancesModel.Width = *containerResourceOpsParam.Width
	//instancesModel.Height = *containerResourceOpsParam.Height
	//instancesModel.Fps = *containerResourceOpsParam.Fps
	//instancesModel.AdiTemplateId = realPhoneModel.Id
	err = instancesModel.UpdatePartFields(db, updateFiles)
	if err != nil {
		glog.Errorf("update instance failed:err %v", err)
		return err
	}
	err = instanceModel.UpdatePartFields(db, map[string]interface{}{"state": 0, "operate_time": time.Now()})
	if err != nil {
		glog.Errorf("update instance failed:err %v", err)
		return err
	}
	return nil
}

type ContainerResourceOpsParam struct {
	Async              *bool                `json:"async"`
	Name               string               `json:"name"`
	Ip                 string               `json:"ip"`
	CpuLimit           *int                 `json:"cpuLimit"`
	MemoryLimit        *int                 `json:"memoryLimit"`
	Hostname           string               `json:"hostname"`
	IsolateDisk        *bool                `json:"isolateDisk"`
	ExtId              string               `json:"extId"`
	MacvlanName        string               `json:"macvlanName"`
	ContainerIndex     *int                 `json:"containerIndex"`
	DiskOpsParam       *BaseLvmDiskOpsParam `json:"diskOpsParam"`
	StorageLimit       int                  `json:"storageLimit"`
	DownloadUrlOfADI   string               `json:"downloadUrlOfADI"`
	PasswordOfADI      string               `json:"passwordOfADI"`
	DeviceAndroidProps map[string]string    `json:"deviceAndroidProps"`
	AndroidCertData    string               `json:"androidCertData"`
	ImageRepository    string               `json:"imageRepository"`
	ImageTag           string               `json:"imageTag"`
	Mac                string               `json:"mac"`
	ClearContainerData *bool                `json:"clearContainerData"`
	Width              *int                 `json:"width"`
	Height             *int                 `json:"height"`
	Fps                *int                 `json:"fps"`
	Dpi                *int                 `json:"dpi"`
	GameServerAddress  string               `json:"gameServerAddress"`
	Dns1               string               `json:"dns1"`
	Dns2               string               `json:"dns2"`
	CreateVersion      string               `json:"createVersion"`
	Ports              string               `json:"ports"`
}
type BaseLvmDiskOpsParam struct {
	ContainerPerStorageSize *int
}

func EasyToRecreateNewInstance(instanceUseId int64, userId string) error {
	db, err := composite.Database.GetOrm()
	if err != nil {
		return err
	}
	instanceModel := &resources.InstanceUses{Id: instanceUseId}
	err = instanceModel.GetByIdWithInstanceInfo(db)
	if err != nil {
		glog.Errorf("get instance failed:err %v", err)
		return err
	}
	if instanceModel.UserId != userId {
		return fmt.Errorf("no permission")
	}
	androidVersion, _ := strconv.Atoi(instanceModel.Instances.ImageTag)
	if androidVersion == 0 {
		androidVersion = 13
	}
	productModel := &products.Products{Id: instanceModel.Instances.ProductId}
	err = productModel.GetById(db)
	if err != nil {
		return err
	}
	var containerResourceOpsParam ContainerResourceOpsParam
	containerResourceOpsParam.Name = instanceModel.Instances.Name
	containerResourceOpsParam.Ip = instanceModel.Instances.Ip
	containerResourceOpsParam.CpuLimit = &(instanceModel.Instances.CpuCores)
	containerResourceOpsParam.MemoryLimit = &(instanceModel.Instances.Memory)
	containerResourceOpsParam.Hostname = instanceModel.Instances.Name
	containerResourceOpsParam.MacvlanName = instanceModel.Instances.MacVlanName
	containerResourceOpsParam.ContainerIndex = &(instanceModel.Instances.Index)
	storage := int(instanceModel.Instances.Storage)
	containerResourceOpsParam.DiskOpsParam = &BaseLvmDiskOpsParam{
		ContainerPerStorageSize: &storage,
	}
	containerResourceOpsParam.StorageLimit = storage
	containerResourceOpsParam.ImageRepository = instanceModel.Instances.Image //TODO 暂时写死
	containerResourceOpsParam.ImageTag = "latest"
	containerResourceOpsParam.Mac, _ = utils.GenerateRandomMAC()
	containerResourceOpsParam.DeviceAndroidProps = map[string]string{"persist.sys.cloud.madb_enable": "1", "ro.boot.cluster_code": "1234et", "persist.sys.locale": "zh-CN", "ro.build.version.security_patch": "2025-06-05", "ro.vendor.build.security_patch": "2025-06-05"}
	updateFiles := map[string]interface{}{
		"mac": containerResourceOpsParam.Mac,
	}
	if instanceModel.ProxyId != 0 {
		props, err := GetCountryParamsForInstance(instanceModel.Id)
		if err != nil {
			fmt.Printf("get proxy country params failed:err %v", err)
			//return err
		}
		for k, v := range props {
			containerResourceOpsParam.DeviceAndroidProps[k] = v
		}
	}
	if productModel.Type == 1 { //标准云机
		width := 720
		height := 1280
		dpi := 360
		fps := 30
		containerResourceOpsParam.Width = &width
		containerResourceOpsParam.Height = &height
		containerResourceOpsParam.Fps = &fps
		containerResourceOpsParam.Dpi = &dpi
	} else {
		realPhoneModel := &realphone.RealPhoneTemplate{AndroidImageVersion: androidVersion}
		err = realPhoneModel.GetRandButNotOldOneByAndroidVersion(db, androidVersion, int(instanceModel.Instances.AdiTemplateId))
		if err != nil {
			return err
		}
		containerResourceOpsParam.DownloadUrlOfADI = realPhoneModel.AdiTemplateDownloadUrl
		containerResourceOpsParam.PasswordOfADI = realPhoneModel.AdiTemplatePwd
		certificateModel := &realphone.CertificateRepository{
			CertificateLevel: 3,
		}
		err = certificateModel.GetOneRandByLevel(db)
		if err != nil {
			return err
		}
		layoutArr := strings.Split(strings.Replace(realPhoneModel.ScreenLayoutCode, "realdevice_", "", -1), "x")
		width := instanceModel.Instances.Width
		height := instanceModel.Instances.Height
		dpi := instanceModel.Instances.Dpi
		if layoutArr != nil && len(layoutArr) == 3 {
			width, _ = strconv.Atoi(layoutArr[0])
			height, _ = strconv.Atoi(layoutArr[1])
			dpi, _ = strconv.Atoi(layoutArr[2])
		}
		containerResourceOpsParam.AndroidCertData = certificateModel.Certificate

		containerResourceOpsParam.Width = &width
		containerResourceOpsParam.Height = &height
		containerResourceOpsParam.Fps = &(instanceModel.Instances.Fps)
		containerResourceOpsParam.Dpi = &dpi
		updateFiles["adi_template_id"] = realPhoneModel.Id
	}

	containerResourceOpsParam.GameServerAddress = "192.168.1.1:8081"
	containerResourceOpsParam.Dns1 = "8.8.8.8"
	containerResourceOpsParam.Ports = strconv.Itoa(instanceModel.Instances.AdbPort)
	clearContainerData := true
	containerResourceOpsParam.ClearContainerData = &clearContainerData
	go func(param ContainerResourceOpsParam) {
		url := fmt.Sprintf("http://%s:%d/container/lifecycle/recreate", instanceModel.Instances.Machine.Ip, instanceModel.Instances.Machine.Port)
		// 将数据编码为 JSON
		jsonData, err := json.Marshal(param)
		if err != nil {
			fmt.Printf("Get system info failed! json marshall err:%v", err)
			return
		}

		// 创建 POST 请求
		resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
		if err != nil {
			fmt.Printf("Get system info failed! post err:%v", err)
			return
		}
		defer resp.Body.Close()
		if resp.StatusCode != http.StatusOK {
			fmt.Printf("Get system info failed! status code:%d", resp.StatusCode)
			return
		}
		// 读取响应
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			fmt.Printf("Get system info failed! read body err:%v", err)
			return
		}
		fmt.Println(string(body))
		return
	}(containerResourceOpsParam)
	instancesModel := &instanceModel.Instances
	//updateFiles := map[string]interface{}{
	//	"dpi":             *containerResourceOpsParam.Dpi,
	//	"width":           *containerResourceOpsParam.Width,
	//	"height":          *containerResourceOpsParam.Height,
	//	"fps":             *containerResourceOpsParam.Fps,
	//	"adi_template_id": realPhoneModel.Id,
	//	"mac":             containerResourceOpsParam.Mac,
	//}
	updateFiles["dpi"] = *containerResourceOpsParam.Dpi
	updateFiles["width"] = *containerResourceOpsParam.Width
	updateFiles["height"] = *containerResourceOpsParam.Height
	updateFiles["fps"] = *containerResourceOpsParam.Fps

	//instancesModel.Dpi = *containerResourceOpsParam.Dpi
	//instancesModel.Width = *containerResourceOpsParam.Width
	//instancesModel.Height = *containerResourceOpsParam.Height
	//instancesModel.Fps = *containerResourceOpsParam.Fps
	//instancesModel.AdiTemplateId = realPhoneModel.Id
	err = instancesModel.UpdatePartFields(db, updateFiles)
	if err != nil {
		glog.Errorf("update instance failed:err %v", err)
		return err
	}
	err = instanceModel.UpdatePartFields(db, map[string]interface{}{"state": 0, "operate_time": time.Now()})
	if err != nil {
		glog.Errorf("update instance failed:err %v", err)
		return err
	}
	return nil
}

type ResetPhoneDataParam struct {
	InstanceUseId []int64 `json:"instance_use_ids"`
}

func ResetPhoneData(InstanceUseId int64, userId string) error {

	db, err := composite.Database.GetOrm()
	if err != nil {
		glog.Errorf("get db failed:err %v", err)
		return err
	}
	instanceModel := resources.InstanceUses{
		Id: InstanceUseId,
	}
	err = instanceModel.GetByIdWithInstanceInfo(db)
	if err != nil {
		glog.Errorf("get instance failed:err %v", err)
		return err
	}
	if instanceModel.UserId != userId {
		return fmt.Errorf("no permission")
	}
	var containerResourceOpsParam ContainerResourceOpsParam
	containerResourceOpsParam.Name = instanceModel.Instances.Name
	go func(param ContainerResourceOpsParam) {
		url := fmt.Sprintf("http://%s:%d/container/lifecycle/reset", instanceModel.Instances.Machine.Ip, instanceModel.Instances.Machine.Port)
		// 将数据编码为 JSON
		jsonData, err := json.Marshal(param)
		if err != nil {
			fmt.Printf("Get system info failed! json marshall err:%v", err)
			return
		}

		// 创建 POST 请求
		resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
		if err != nil {
			fmt.Printf("Get system info failed! post err:%v", err)
			return
		}
		defer resp.Body.Close()
		if resp.StatusCode != http.StatusOK {
			fmt.Printf("Get system info failed! status code:%d", resp.StatusCode)
			return
		}
		// 读取响应
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			fmt.Printf("Get system info failed! read body err:%v", err)
			return
		}
		fmt.Println(string(body))
		return
	}(containerResourceOpsParam)

	err = instanceModel.UpdatePartFields(db, map[string]interface{}{"state": 0, "operate_time": time.Now()})
	if err != nil {
		glog.Errorf("update instance failed:err %v", err)
		return err
	}
	return nil
}

func GetCountryParamsForInstance(instanceUseId int64) (map[string]string, error) {
	countryParams := make(map[string]string)
	db, err := composite.Database.GetOrm()
	if err != nil {
		return countryParams, err
	}
	InstanceUseModel := resources.InstanceUses{Id: instanceUseId}
	err = InstanceUseModel.GetByIdWithInstanceInfo(db)
	if err != nil {
		return countryParams, err
	}
	ProxyModel := &proxy2.Proxy{Id: InstanceUseModel.ProxyId}
	err = ProxyModel.GetById(db)
	if err != nil {
		return countryParams, err
	}
	//udid := fmt.Sprintf("%s:%d", InstanceUseModel.Instances.Machine.Ip, InstanceUseModel.Instances.AdbPort)
	CountryModel := country.CountryInfo{CountryCode: ProxyModel.CountryCode}
	err = CountryModel.GetCountryCode(db)
	if err != nil {
		return countryParams, err
	}
	simInfoModel := country.SimInfo{CountryCode: ProxyModel.CountryCode}
	list, err := simInfoModel.GetByCountryCode(db)
	if err != nil {
		return countryParams, err
	}
	len_ := len(list)
	// 设置随机种子，否则每次运行结果一样
	rand.Seed(time.Now().UnixNano())
	x := rand.Intn(len_ - 1)
	simInfo := list[x]
	mcc := simInfo.Mcc
	mnc := simInfo.Mnc
	phonenum, err := reggen.Generate(simInfo.PhoneRegex, 1)
	if err != nil {
		//return err
		fmt.Println(err)
	}
	countryParams["persist.sys.cloud.phonenum"] = phonenum
	iccid, err := reggen.Generate(simInfo.IccidRegex, 1)
	if err != nil {
		fmt.Println(err)
	}
	countryParams["persist.sys.cloud.iccidnum"] = iccid
	imei, err := reggen.Generate(simInfo.ImeiRegex, 1)
	if err != nil {
		fmt.Println(err)
	}
	countryParams["persist.sys.cloud.imeinum"] = imei
	imsi, err := reggen.Generate(simInfo.ImsiRegex, 1)
	if err != nil {
		fmt.Println(err)
	}
	countryParams["persist.sys.cloud.imsinum"] = imsi
	rand.Seed(time.Now().UnixNano())
	// 生成 [0, 0xFFF] 之间的随机整数
	n := rand.Intn(0x1000)
	tac := fmt.Sprintf("%03X", n)
	rand.Seed(time.Now().UnixNano())
	c := rand.Intn(0x10000000)
	cellid := fmt.Sprintf("%07X", c)
	rand.Seed(time.Now().UnixNano())
	e := rand.Intn(0x1000)
	narfcn := fmt.Sprintf("%03X", e)
	f := rand.Intn(0x100)
	physicalcellid := fmt.Sprintf("%02X", f)

	cellinfo := "9," + mcc + "," + mnc + "," + tac + "," + cellid + "," + narfcn + "," + physicalcellid
	countryParams["persist.sys.cloud.cellinfo"] = cellinfo

	if ProxyModel.Lat != "" {
		countryParams["persist.sys.cloud.gps.lat"] = ProxyModel.Lat
	}
	if ProxyModel.Lon != "" {
		countryParams["persist.sys.cloud.gps.lon"] = ProxyModel.Lon
	}
	countryParams["persist.sys.cloud.gps.speed"] = "0.1"
	countryParams["persist.sys.cloud.gps.altitude"] = "15"
	countryParams["persist.sys.cloud.gps.bearing"] = "73"
	if ProxyModel.Timezone != "" {
		countryParams["persist.sys.timezone"] = ProxyModel.Timezone
	}
	countryParams["persist.sys.cloud.mobileinfo"] = mcc + "," + mnc
	countryParams["ro.sys.cloud.proxy.type"] = ProxyModel.Protocol
	countryParams["ro.sys.cloud.proxy.mode"] = "vpn"
	countryParams["ro.sys.cloud.proxy.data"] = fmt.Sprintf("%s|%d|%s|%s|true", ProxyModel.Host, ProxyModel.Port, ProxyModel.UserName, ProxyModel.Password)
	return countryParams, nil
}
